<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yunwuxin <448901948@qq.com>
// +----------------------------------------------------------------------

namespace randy\queue;

use InvalidArgumentException;

abstract class Connector {
	protected $options = [];

	/**
	 *
	 * @param string      $job_name 任务名称
	 * @param string      $job      任务执行脚本
	 * @param string      $data     任务数据
	 * @param string|null $queue    队列名称
	 *
	 * @return mixed
	 * @author : Randy_chen
	 * @Date   : 2020/9/2
	 * @Time   : 22:12
	 */
	abstract public function push($job_name, $job, string $data = '', $queue = null);

	abstract public function later($job_name, $job, $data = '', $delay = 0, $queue = null);

	abstract public function pop($queue = null);

	public function marshal() {
		throw new \RuntimeException('pop queues not support for this type');
	}

	protected function createPayload($job, $data = '', $job_name = null) {
		if (is_object($job)) {
			$payload = json_encode([
				                       'job'  => 'think\queue\CallQueuedHandler@call',
				                       'data' => [
					                       'commandName' => get_class($job),
					                       'command'     => serialize(clone $job),
				                       ],
			                       ]);
		} else {
			$payload = json_encode($this->createPlainPayload($job, $data));
		}

		if (JSON_ERROR_NONE !== json_last_error()) {
			throw new InvalidArgumentException('Unable to create payload: ' . json_last_error_msg());
		}

		return $payload;
	}

	protected function createPlainPayload($job, $data) {
		return [
			'job'      => $job,
			'data'     => $data,
			'attempts' => 0
		];
	}

	protected function setMeta($payload, $key, $value) {
		$payload = json_decode($payload, true);
		$payload[$key] = $value;
		$payload = json_encode($payload, JSON_UNESCAPED_UNICODE);

		if (JSON_ERROR_NONE !== json_last_error()) {
			throw new InvalidArgumentException('Unable to create payload: ' . json_last_error_msg());
		}

		return $payload;
	}
}
